import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/main/entity/commo_spec4app_record_entity.dart';
import 'package:shopping_group/modle/main/entity/id_name_entity.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';

class MainDataBloc implements BlocBase {
  List<IdNameEntity> _listType = [];
  List<CommoSpec4AppRecordEntity> _listEntity = [];

  String _hasMore = '0';
  int _pageNo = 1;
  String _type = 'CST_NON_TE_4_DS';

  ScrollController _scrollController;
  // Stream来处理计数器
  StreamController<Object> _initController = StreamController<Object>();
  StreamSink<Object> get initMainData => _initController.sink;

  StreamController<Object> _initCommSpecController = StreamController<Object>();
  StreamSink<Object> get initCommSpecData => _initCommSpecController.sink;

  StreamController<Object> _commSpecController = StreamController<Object>();
  StreamSink<Object> get _addCommSpecData => _commSpecController.sink;
  Stream<Object> get sendCommSpecData => _commSpecController.stream;

  StreamController<Object> _aucController = StreamController<Object>();
  StreamSink<Object> get _addTypeData => _aucController.sink;
  Stream<Object> get sendTypeData => _aucController.stream;

  //处理more响应
  StreamController<ScrollController> _actionMoreController = StreamController<ScrollController>();
  StreamSink get moreDate => _actionMoreController.sink;

  //处理上拉刷新
  StreamController<ScrollController> _actionRefreshController = StreamController<ScrollController>();
  StreamSink get refreshDate => _actionRefreshController.sink;

  MainDataBloc() {
    _initController.stream.listen(initTypeData);
    _initCommSpecController.stream.listen(commSpecData);
    _actionMoreController.stream.listen(loadMoreData);
    _actionRefreshController.stream.listen(refreshData);
  }

  void commSpecData(data) {
    if (data is String) {
      _type = data;
      _listCommSpecTask(1);
    } else if (data is List) {
      _addCommSpecData.add(data);
    }
  }

  void initTypeData(data) {
    if (data is List) {
      _addTypeData.add(data);
    } else {
      Future.wait([_initTypeTask(), _listCommSpecTask(1)]);
    }
  }

  void refreshData(data) {
    if (data is String) {
      _type = data;
      _pageNo = 1;
      _listEntity?.clear();
      _listCommSpecTask(_pageNo.toString());
    }
  }

  void loadMoreData(controller) {
    if (controller is ScrollController) {
      _scrollController = controller;
      var maxScroll = _scrollController.position.maxScrollExtent;
      var pixel = _scrollController.position.pixels;
      var count = _listEntity.length;
      var length = int.parse(_hasMore);
      if (maxScroll == pixel && count > 0 && count < length) {
        _pageNo++;
        _listCommSpecTask(_pageNo);
      }
    }
  }

  Future _listCommSpecTask(pageNo) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext).requestFocus(FocusNode());
    Map<String, dynamic> data = {};
    data['val'] = _type;
    data['pageIndex'] = pageNo;
    data['pageSize'] = BaseConstant.PAGE_MAX_SIZE;
    // LogUtil.e(data.toString(),
    //     tag: '_listCommSpecTask......................////////////');
    HttpUtilAll.post(Apis.AUC_COMMO_URL, data: data, headers: {}, success: (result) {
      _listEntity?.clear();
      // 请求成功返回的数据
      if (null != result) {
        List list = List.from(result);
        for (var item in list) {
          CommoSpec4AppRecordEntity params = CommoSpec4AppRecordEntity.fromJson(item);
          _listEntity.add(params);
        }
      }
      _addCommSpecData.add(_listEntity);
      // eventBus.fire(CommoSpecEvent(_listEntity, _type));
    }, error: (errorMsg) {
      // 请求失败返回的错误信息
      BotToast.showText(text: errorMsg);
    });
  }

  Future _initTypeTask() async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext).requestFocus(FocusNode());

    // BotToast.showLoading();
    HttpUtilAll.post(Apis.AUC_MAIN_TREE_URL, data: {}, headers: {}, success: (result) {
      // 请求成功返回的数据
      if (null != result) {
        List list = List.from(result);
        for (var item in list) {
          IdNameEntity params = IdNameEntity.fromJson(item);
          _listType.add(params);
        }
      }

      _listType.forEach((IdNameEntity element) {
        if (element.children.length > 0) {
          element.children.forEach((IdNameEntity subEntity) {
            if (subEntity.id == "CST_NON_TE_4_DS") {
              subEntity.isSelect = true;
            }
          });
        } else {
          if (element.id == "CST_NON_TE_4_DS") {
            element.isSelect = true;
          }
        }
      });

      // IdNameEntity entity = _listType.first;
      // if (ObjectUtil.isEmptyString(entity.parentPdId)) {
      //   IdNameEntity chEntity = entity.children.first;
      //   chEntity
      //     ..color = Colours.title_white
      //     ..radiusColor = Colours.yanqi_red
      //     ..isSelect = true;
      // }
      _addTypeData.add(_listType);
      // eventBus.fire(TypeMainEvent(_listType));
    }, error: (errorMsg) {
      // 请求失败返回的错误信息
      BotToast.showText(text: errorMsg);
    });
  }

  @override
  void dispose() {
    _initController?.close();
    _aucController?.close();
    _initCommSpecController?.close();
    _commSpecController?.close();
    _actionMoreController?.close();
    _actionRefreshController?.close();
  }
}
